/*
 *    DynamicArffFileStream.java
 *    @author Manuel Baena (mbaena@uma.es)
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package moa.streams;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import moa.core.InputStreamProgressMonitor;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.core.converters.DynamicArffLoader;
import moa.options.AbstractOptionHandler;
import moa.options.FileOption;
import moa.options.IntOption;
import moa.tasks.TaskMonitor;
import weka.core.Instance;

/**
 * Stream reader of DARFF files.
 *
 * @author Manuel Baena (mbaena@uma.es)
 * @version $Revision: 7 $
 */
public class DynamicArffFileStream extends AbstractOptionHandler implements
        DynamicInstanceStream {

    @Override
    public String getPurposeString() {
        return "A stream read from an DARFF file.";
    }

    private static final long serialVersionUID = 1L;

    public FileOption darffFileOption = new FileOption("darffFile", 'f',
            "DARFF file to load.", null, "arff", false);

    public IntOption classIndexOption = new IntOption(
            "classIndex",
            'c',
            "Class index of data. 0 for none or -1 for last attribute in file.",
            -1, -1, Integer.MAX_VALUE);

    protected InstancesHeader instancesHeader;
    
    protected DynamicArffLoader darffLoader;

    protected boolean hitEndOfFile;

    protected Instance lastInstanceRead;
    
    protected List<StructuralChangeInstance> lastStructuralChangesRead;

    protected int numInstancesRead;

    protected InputStreamProgressMonitor fileProgressMonitor;

    public DynamicArffFileStream(String darffFileName, int classIndex) {
        this.darffFileOption.setValue(darffFileName);
        this.classIndexOption.setValue(classIndex);
        restart();
    }

    @Override
    public void prepareForUseImpl(TaskMonitor monitor,
            ObjectRepository repository) {
        restart();
    }

    @Override
    public InstancesHeader getHeader() {
        return instancesHeader;
    }

    @Override
    public long estimatedRemainingInstances() {
        double progressFraction = this.fileProgressMonitor.getProgressFraction();
        if ((progressFraction > 0.0) && (this.numInstancesRead > 0)) {
            return (long) ((this.numInstancesRead / progressFraction) - this.numInstancesRead);
        }
        return -1;
    }

    @Override
    public boolean hasMoreInstances() {
        return !this.hitEndOfFile;
    }

    @Override
    public Instance nextInstance() {
		if (this.lastStructuralChangesRead != null && this.lastStructuralChangesRead.size() > 0) {
			return this.lastStructuralChangesRead.remove(0);
		}
        Instance prevInstance = this.lastInstanceRead;
        readNextInstanceFromFile();
        return prevInstance;
    }

    @Override
    public boolean isRestartable() {
        return true;
    }

    @Override
    public void restart() {
        try {
            if (this.fileProgressMonitor != null) {
                this.fileProgressMonitor.close();
            }
            InputStream fileStream = new FileInputStream(this.darffFileOption.getFile());
            this.fileProgressMonitor = new InputStreamProgressMonitor(
                    fileStream);
            
            darffLoader = new DynamicArffLoader();
            darffLoader.setSource(fileProgressMonitor);
            
            instancesHeader = new InstancesHeader(darffLoader.getStructure());
            
            if (this.classIndexOption.getValue() < 0) {
                this.instancesHeader.setClassIndex(this.instancesHeader.numAttributes() - 1);
            } else if (this.classIndexOption.getValue() > 0) {
                this.instancesHeader.setClassIndex(this.classIndexOption.getValue() - 1);
            }
            this.numInstancesRead = 0;
            this.lastInstanceRead = null;
            readNextInstanceFromFile();
        } catch (IOException ioe) {
            throw new RuntimeException("ArffFileStream restart failed.", ioe);
        }
    }

    protected boolean readNextInstanceFromFile() {
        try {
        	this.lastInstanceRead = this.darffLoader.getNextInstance(instancesHeader);
        	this.lastStructuralChangesRead = this.darffLoader.getNextStructuralChanges();
        	
            if (lastInstanceRead != null) {
                this.numInstancesRead++;
                this.hitEndOfFile = false;
                return true;
            }
            if (this.fileProgressMonitor != null) {
                this.fileProgressMonitor.close();
                this.fileProgressMonitor = null;
            }
            this.hitEndOfFile = true;
            return false;
        } catch (IOException ioe) {
            throw new RuntimeException(
                    "DynamicArffFileStream failed to read instance from stream.", ioe);
        }
    }

    @Override
    public void getDescription(StringBuilder sb, int indent) {
        // TODO Auto-generated method stub
    }

}
